package com.letv.android.client.webview;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.letv.core.db.PreferencesManager;
import com.letv.core.utils.LogInfo;

/**
 * 向服务器同步用户登录登出状态并查看服务器响应在H5中的结果
 */
public class SyncUserStateUtil {
    private static boolean mIsSyncUserStateSuccessWithH5 = false;// 标志是否同步过登录登出状态并且成功
    private GetUserloginStateListener mListener;
    private static final String USER_STATUS_URL = "http://sso.letv.com/user/setUserStatus";

    public SyncUserStateUtil(GetUserloginStateListener listener) {
        this.mListener = listener;
    }

    /**
     * 获取同步工具实例
     *
     * @return 同步工具
     */
    public static SyncUserStateUtil getUserStateUtil() {
        return new SyncUserStateUtil(null);
    }

    /**
     * 获取同步工具实例 并添加结果监听
     *
     * @param listener 同步结果监听
     * @return 同步工具
     */
    public static SyncUserStateUtil getUserStateUtil(GetUserloginStateListener listener) {
        return new SyncUserStateUtil(listener);
    }

    public interface GetUserloginStateListener {
        void onSyncSuccessed();

        void onSyncFailed();
    }

    /**
     * 是否需要同步登陆状态
     *
     * @return true : 需要同步 false：不需要同步
     */
    public static boolean isNeedSyncUserState() {
        return !mIsSyncUserStateSuccessWithH5;
    }

    /**
     * 请求地址: http://sso.letv.com/user/setUserStatus?tk={tk}&from={from}&next_action={next_action}
     * 获取setUserStatus接口的地址
     *
     * @return 同步用户状态url
     */
    public static String getSyncUserStateUrl() {
        String webSsoUrl = "";
        if (PreferencesManager.getInstance().isLogin()) {
            String ssoTk = PreferencesManager.getInstance().getSso_tk();
            if (!TextUtils.isEmpty(ssoTk)) {
                //客户端设置主页登录状态
                webSsoUrl = USER_STATUS_URL + "?tk=" + ssoTk + "&from=mobile_tv";
            }
        } else {
            webSsoUrl = USER_STATUS_URL + "?tk=" + "&from=mobile_tv";
        }
        return webSsoUrl;
    }

    /**
     * 处理同步结果
     * data: {"bean":["51301085"],"action":"setUserStatus","responseType":"json","status":"1",
     * "errorCode":"0","message":"\u767b\u5f55\u6210\u529f"}
     */
    class JSHandler {
        @JavascriptInterface
        public void show(String data) {
            LogInfo.log("wlx", "data: " + data);
            try {
                String errorCode = (new JSONObject(data)).getString("errorCode");
                if ("0".equals(errorCode)) {
                    if (mListener != null) {
                        mListener.onSyncSuccessed();
                    }
                    LogInfo.log("wlx", "同步状态成功");
                    mIsSyncUserStateSuccessWithH5 = true;
                } else {
                    if (mListener != null) {
                        mListener.onSyncFailed();
                    }
                    LogInfo.log("wlx", "同步状态失败");
                    mIsSyncUserStateSuccessWithH5 = false;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 带异步请求同步结果的
     */
    @SuppressLint("AddJavascriptInterface")
    public synchronized void syncUserStateByAsync(Context context) {
        LogInfo.log("wlx", "通知WebView客户端登录登出状态");
        mIsSyncUserStateSuccessWithH5 = false;
        WebView webView = new WebView(context);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JSHandler(), "jshandler");
        webView.setVisibility(View.GONE);
        webView.loadUrl(getSyncUserStateUrl());//通知WebView客户端登录登出状态
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                LogInfo.log("wlx", "onPageFinished url: " + url);
                view.loadUrl("javascript:window.jshandler.show(document.body.innerText);");
            }
        });
    }

    /**
     * 用户状态是否同步成功
     *
     * @return true：同步成功 false：同步失败
     */
    public static boolean isSyncUserStateSuccessWithH5() {
        return mIsSyncUserStateSuccessWithH5;
    }

}
